package com.example.administrator.chinafood;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.administrator.chinafood.SQLite.MyDBOpenHelper;

public class Login extends AppCompatActivity {

    private Button btn_login ;
    private Button btn_register;
    private EditText ed_username;
    private EditText ed_password;

    String username;
    String password;

    private MyDBOpenHelper myDBOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        myDBOpenHelper = new MyDBOpenHelper(Login.this,"ChinaFood.db");
        init();

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = ed_username.getText().toString();
                password = ed_password.getText().toString();
                userLogin();
            }
        });

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(Login.this,Register.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void init(){
        btn_login = (Button)findViewById(R.id.login_btn_login);
        btn_register = (Button)findViewById(R.id.login_btn_register);
        ed_username = (EditText)findViewById(R.id.login_ed_username);
        ed_password = (EditText)findViewById(R.id.login_ed_password);
    }

    private void userLogin (){
        SQLiteDatabase db = myDBOpenHelper.getReadableDatabase();
        String db_username;
        String db_password;
        Cursor cursor = db.rawQuery("select * from user where username = ?",new String[]{username});
        if (cursor.getCount() == 1){
            cursor.moveToFirst();
            db_username = cursor.getString(cursor.getColumnIndex("username"));
            db_password = cursor.getString(cursor.getColumnIndex("password"));
            if (username.equals(db_username) && password.equals(db_password)){
                Intent intent = new Intent();
                intent.setClass(Login.this,MainActivity.class);
                startActivity(intent);
                finish();
            }else{
                Toast.makeText(Login.this,"用户名或者密码错误",Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(Login.this,"用户不存在",Toast.LENGTH_SHORT).show();
        }
        cursor.close();
        db.close();
    }
}
